﻿using Microsoft.Extensions.Logging;
using Ops.Exchange.Forwarder;
using Ops.Host.Core.Management;
using Ops.Host.Core.Models;
using Ops.Host.Core.Utils;

namespace Ops.Host.Core.Services;

internal sealed class NoticeService : INoticeService
{
    private readonly IFreeSql _freeSql;
    private readonly ILogger _logger;

    public NoticeService(IFreeSql freeSql, ILogger<NoticeService> logger)
    {
        _freeSql = freeSql;
        _logger = logger;
    }

    private const string PLC_Notice_Energy_1 = nameof(PLC_Notice_Energy_1); // 能耗（有功）
    private const string PLC_Notice_Energy_2 = nameof(PLC_Notice_Energy_2); // 能耗（无功）

    public async Task<ReplyResult> SaveNoticeAsync(ForwardData data)
    {
        // 能耗
        if (data.Tag == PLC_Notice_Energy_1)
        {
            return await SaveEnergyConsumeAsync(data, 1);
        }

        if (data.Tag == PLC_Notice_Energy_2)
        {
            return await SaveEnergyConsumeAsync(data, 2);
        }

        return ReplyResultHelper.Ok();
    }

    private async Task<ReplyResult> SaveEnergyConsumeAsync(ForwardData data, int category)
    {
        try
        {
            var energy = data.GetReal(data.Tag);

            EnergyConsumption item = new()
            {
                Station = data.Schema.Station,
                Category = category,
                Desc = category switch
                {
                    1 => "用功",
                    2 => "无功",
                    _ => "",
                },
                Energy = (decimal)energy.GetValueOrDefault(),
                CreatedAt = DateTime.Now,
            };

            await _freeSql.Insert(item).ExecuteAffrowsAsync();

            // 推送消息
            await MessageTaskQueueManager.Default.QueueAsync(new Message(item.Station, MessageClassify.Energy, category.ToString(), energy));

            return ReplyResultHelper.Ok();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"[NoticeService] Error Tag：{data.Tag}");
            return ReplyResultHelper.Error();
        }
    }
}
